<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 跨境宝项目 - ERP接口类
 * @author   yuhaibo <yuhaibo@ebsig.com>
 * @version 1.0
 */

namespace App\Service\Rpc\Erp;

use Carbon\Carbon;

use GuzzleHttp\Client;

use App\Models\Bill\Bill;  //订单主表

use App\Models\Bill\BillPay; //订单支付

use App\Models\Bill\ThirdBill; //订单传输记录表

use App\Models\Bill\LogEaiBill; //订单接口日志

use App\Models\Bill\BillGoods; //订单商品表

use App\Models\Goods\GoodsSale;

use App\Models\Customer\Customer;

use App\Models\ConfigureFunction;

class KjbErp
{

    /**
     * 接口请求地址
     */
    private $http_url  = 'http://test.cqkjb.cn:71/sendOrder';

    private $bill_no = 0;

    private $key = 'da0205c1e0aa9512';

    private function pkcs5Pad($text)
    {
        $cipher = MCRYPT_RIJNDAEL_128;
        $modes = MCRYPT_MODE_ECB;
        $blocksize = mcrypt_get_block_size ( $cipher, $modes );
        $pad = $blocksize - (strlen ( $text ) % $blocksize);
        return $text . str_repeat ( chr ( $pad ), $pad );
    }

    // 报文加密
    private function encrypt($str,$key)
    {
        $cipher = MCRYPT_RIJNDAEL_128;        //加密类型
        $mode = MCRYPT_MODE_ECB;            //加密模式
        $str = $this->pkcs5Pad($str);
        $str_encrypt = mcrypt_encrypt($cipher,$key,$str,$mode);
        return base64_encode($str_encrypt);
    }

    /**
     * 请求接口，并保存日志
     * @param string $request_url 请求链接
     * @param string $api_name 接口名称
     * @param array $get_data get请求数据
     * @param array $post_data post请求数据
     * @param string $request_way 请求方式
     * @return array
     */
    public function requestApi( $request_url, $api_name, $get_data = array(), $post_data = array(), $request_way = 'post' )
    {

        $client = new Client();

        //接口请求开始时间
        $start_time = microtime(true);

       $res = $client->post($request_url,['form_params'=>[
           'headers' =>[
               'Accept' => 'application/json',
               'Content-Type' => 'multipart/form-data;charset=utf-8'
           ],
           'data' => $post_data
       ]]);

        //接口请求结束时间
        $end_time = microtime(true);

        $result_array = json_decode($res->getBody(),true);

        $return_data = [];
        if ($result_array['code'] == 0) {
            $return_data['code'] = 200;
            $return_data['message'] = $result_array['message'];

        } else {
            $return_data['code'] = 400;
            $return_data['message'] = $result_array['message'];
        }

        //记录日志
        $log_eai_bill = new LogEaiBill();
        $log_eai_bill->uuid = makeUuid();
        $log_eai_bill->timeStamp = Carbon::now();
        $log_eai_bill->creator = 'KjbErp';
        $log_eai_bill->createTime = Carbon::now();
        $log_eai_bill->bill_no = $this->bill_no;
        $log_eai_bill->api_name = $api_name;
        if ( $request_way == 'post' ) {
            $log_eai_bill->request_data = print_r($post_data, true);
        } else {
            $log_eai_bill->request_data = print_r($get_data, true);
        }
        $log_eai_bill->return_data = print_r($return_data, true);
        $log_eai_bill->return_code = $return_data['code'];
        $log_eai_bill->return_msg  = $return_data['message'];
        $log_eai_bill->exec_time = ($end_time - $start_time) * 1000;
        $log_eai_bill->save();

        return $return_data;

    }

    /**
     * 生成订单传送给线下
     * @param $args_array
     * @return array
     */
    public function createBillPushData($args_array)
    {

        if ( empty($args_array['bill_no']) ) {
            return array('code'=>100001 , 'messsage'=>'订单号不能为空');
        }

        //接口参数
        $bill_data = array();
        //查询订单信息
        $bill_master = Bill::find($args_array['bill_no']);
        if (empty($bill_master)) {
            return array('code'=>100002 , 'messsage'=>'订单信息未找到');
        }

        $bill_master = $bill_master->toArray();

        if ( $bill_master['billChannel'] == 0 ) {
            $bill_master['billChannel'] = 1;
        }

        $bill_data['id'] = 1;
        $bill_data['shopId'] =$bill_master['mallCode'];
        $bill_data['userName'] =$bill_master['custID'];
        $bill_data['sheetId'] = strval($args_array['bill_no']);
        $bill_data['receiver'] = $bill_master['deliver_name'];
        $bill_data['mobile'] = $bill_master['deliver_mobile'];
        $bill_data['province'] = $bill_master['deliver_province'];
        $bill_data['city'] = $bill_master['deliver_city'];
        $bill_data['district'] = $bill_master['deliver_county'];
        $bill_data['address'] = $bill_master['deliver_address'];
        $bill_data['createTime'] = $bill_master['createTime'];//下单时间
        $bill_data['payTime'] = $bill_master['payed_time'];//支付时间
        $bill_data['saleType'] = 'a';//销售类型a=正常，v=取消，r=退货
        $bill_data['orderFrom'] = $bill_master['billChannel'];//订单来源
        $bill_data['memo'] = !empty($bill_master['remark']) ? $bill_master['remark'] : '';
        $bill_data['deliveryType'] = $bill_master['sendTypeID'];//配送方式
        $bill_data['orderAmount'] = $bill_master['bill_totalMoney'];//订单总金额
        $bill_data['payAmount'] = $bill_master['bill_payable'] + $bill_master['bill_balance_money'];//支付金额 + 余额抵扣金额
        $bill_data['freight'] = $bill_master['deliver_feePaid'];//运费
        $bill_data['cross_border'] = $bill_master['bill_cross_border'];//是否是跨境订单

        //查询订单商品信息
        $bill_goods = BillGoods::where('bill_no',$args_array['bill_no'])->get()->toArray();
        if (empty($bill_goods)) {
            return array('code'=>100004 , 'messsage'=>'没有找到商品信息');
        }

        //判断折扣类型
        if ( $bill_master['billType'] == 1 ) {
            $discType = 'n';
        } else {
            $discType = 'p';
        }

        foreach ($bill_goods as $good ) {

            //查询销售商品海关商品编码
            $goods_sale = GoodsSale::select('customs_product_code','goodsType','goodsRate')->find($good['goods_postID']);

            //商品数据
            $bill_data['detail'][] = array(
                'goodsId' => $good['product_code'],
                'goodsType' => isset($goods_sale->goodsType) ? $goods_sale->goodsType : 1 , //商品类型
                'taxRate' => isset($goods_sale->goodsRate) ? $goods_sale->goodsRate : 0.00 , //税率
                'sku' => isset($goods_sale->customs_product_code) ? $goods_sale->customs_product_code : 0,
                'qty' => $good['goods_amount'],
                'price' => $good['goods_purchasePrice'],//售价，顾客为该商品真实支付的金额
                'discount' => number_format(($good['goods_storePrice']-$good['goods_purchasePrice'])*$good['goods_amount'],2,".",""),// 	折扣金额，该商品在原价上优惠的金额
                'saleType' => 'a',// 	销售类型a=正常，v=取消，r=退货
                'discType' => $discType,//折扣类型n=普通 p=促销
                'memo' => !empty($good['goods_remark']) ? $good['goods_remark'] : '',
            );
        }

        //支付方式
        $pay_type_data = explode(',',$bill_master['pay_id_str']);
        if ( empty($pay_type_data) ) {
            return array('code'=>100004 , 'messsage'=>'支付方式信息出错');
        }

        $bill_data['payInfo'] = array();//支付方式数组
        foreach ( $pay_type_data as $pay ) {

            $bill_pay_data = BillPay::where([['bill_no',$args_array['bill_no']],['payTypeID',$pay]])->first();
            if (!$bill_pay_data ) {
                return array('code'=>100004 , 'messsage'=>'没有支付数据');
            }

            $cardNo = '';//支付卡号
            if ( $pay == 2 ) {// '余额',
                $pay_type = 'B';
                $cardNo_data = Customer::select('cardNo')->find($bill_master['pcustID']);
                if ( $cardNo_data && !empty($cardNo_data->cardNo) ){
                    $cardNo = $cardNo_data->cardNo;
                }
            } else if ( $pay == 3 ) {//积分',
                $pay_type = 'h';
            } else if ( $pay == 4 ) {//'支付宝',
                $pay_type = 'A';
            } else if ( $pay == 5 ) {//微信支付',
                $pay_type = 'W';
            } else if ( $pay == 8 ) {// '银联',
                $pay_type = 'N';
            } else if( $pay == 10001 ) { // '提货卡'
                $pay_type = 'V';
            }

            if ( $pay == 3 ) {
                $exchange_rate = ConfigureFunction::getConfigureField(2, 'points_exchange_ratio',100);//会员积分设置
                $bill_pay_data->pay_amount = number_format($bill_pay_data->pay_amount / $exchange_rate , 2,".","");
            }

            $bill_data['payInfo'][] = array(
                'payType' => $pay_type,//支付类型
                'payAmount' => $bill_pay_data->pay_amount ,//支付金额
                'cardNo' => $cardNo,//支付卡号
                'paySn' => !empty($bill_pay_data->pay_code) ? $bill_pay_data->pay_code : null,
            );

        }

        $this->bill_no = $args_array['bill_no'];

//        error_log(var_export($bill_data,true));
//
//        $erp_data = array(
//            'jsonStr' => json_encode($bill_data)
//        );
//
//        $aaa = $this->pushBillToErp($erp_data);
//        return  $aaa;

        return array('code'=>200 , 'messsage'=>'ok', 'data'=>$bill_data);

    }

    /**
     * 推送订单信息到erp系统
     * @param $args_array
     * @return mixed
     */
    public function pushBillToErp($args_array)
    {

        $this->bill_no = $args_array['bill_no'];

        //加密
        $data = $this->encrypt($args_array['jsonStr'],$this->key);

        $return_array  = $this->requestApi($this->http_url , 'pushBillToErp' , array(), $data, 'post' );

        return $return_array;

    }

    /**
     * 订单退款退货
     * @param $args_array
     * @return mixed
     */
    public  function refundrtnreq( $args_array )
    {

        if ( empty($args_array['bill_no']) ) {
            return array('code' => 100001, 'message' => '订单号不能为空');
        }

        $bill_data = ThirdBill::find($args_array['bill_no']);
        if ( !$bill_data || empty($bill_data->jsonStr)) {
            return array('code' => 100002, 'message' => '订单记录信息未找到');
        }

        $bill_array = json_decode($bill_data->jsonStr,true);
        $bill_array['saleType'] = 'r';//退货
        foreach (  $bill_array['detail'] as &$item) {
            $item['saleType'] = 'r';//退货
        }

        $bill_array = json_encode($bill_array);

        $this->bill_no = $args_array['bill_no'];

        //加密
        $data = $this->encrypt($bill_array,$this->key);

        $return_array  = $this->requestApi($this->http_url , 'refundrtnreq' , array(), $data, 'post' );

        return $return_array;

    }

    /**
     * 取消订单
     * @param $args_array
     * @return mixed
     */
    public function cancelBill( $args_array )
    {

        if ( empty($args_array['bill_no']) ) {
            return array('code' => 100001, 'message' => '订单号不能为空');
        }

        $bill_data = ThirdBill::find($args_array['bill_no']);
        if ( !$bill_data || empty($bill_data->jsonStr)) {
            return array('code' => 100002, 'message' => '订单记录信息未找到');
        }

        $bill_array = json_decode($bill_data->jsonStr,true);
        $bill_array['saleType'] = 'v';//取消
        foreach (  $bill_array['detail'] as &$item) {
            $item['saleType'] = 'v';//取消
        }

        $bill_array = json_encode($bill_array);

        $this->bill_no = $args_array['bill_no'];

        //加密
        $data = $this->encrypt($bill_array,$this->key);

        $return_array  = $this->requestApi($this->http_url , 'cancelBill' , array(), $data, 'post' );

        return $return_array;

    }

}